using Microsoft.EntityFrameworkCore;
using RAG.Infrastructure.Data;
using RAG.Domain.Entities.App;

namespace RAG.Application.Services;

/// <summary>
/// 权限检查服务
/// </summary>
public class PermissionCheckService
{
    private readonly RagDbContext _db;

    public PermissionCheckService(RagDbContext db)
    {
        _db = db;
    }

    /// <summary>
    /// 检查用户是否具有指定权限
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="permissionCode">权限代码</param>
    /// <returns>是否具有权限</returns>
    public async Task<bool> HasPermissionAsync(Guid userId, string permissionCode)
    {
        try
        {
            // 先检查用户是否存在
            var user = await _db.Users
                .Include(u => u.Roles)
                .ThenInclude(r => r.Permissions)
                .FirstOrDefaultAsync(u => u.Id == userId && !u.IsDeleted);

            if (user == null)
            {
                Console.WriteLine($"用户不存在: {userId}");
                return false;
            }

            // 检查用户是否有角色
            if (!user.Roles.Any())
            {
                Console.WriteLine($"用户 {userId} 没有任何角色");
                return false;
            }

            // 检查权限
            var hasPermission = user.Roles
                .SelectMany(r => r.Permissions)
                .Any(p => p.PermissionCode == permissionCode);

            Console.WriteLine($"用户 {userId} 检查权限 {permissionCode}: {hasPermission}");
            Console.WriteLine($"用户角色: {string.Join(", ", user.Roles.Select(r => r.RoleName))}");
            Console.WriteLine($"用户权限: {string.Join(", ", user.Roles.SelectMany(r => r.Permissions).Select(p => p.PermissionCode))}");

            return hasPermission;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"权限检查异常: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 检查用户是否具有查看所有数据的权限
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="dataType">数据类型 (document, knowledgebase, qa)</param>
    /// <returns>是否具有查看所有数据的权限</returns>
    public async Task<bool> CanViewAllAsync(Guid userId, string dataType)
    {
        var permissionCode = $"{dataType}.view.all";
        return await HasPermissionAsync(userId, permissionCode);
    }

    /// <summary>
    /// 检查用户是否具有管理权限
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="dataType">数据类型 (document, knowledgebase, qa)</param>
    /// <returns>是否具有管理权限</returns>
    public async Task<bool> CanManageAsync(Guid userId, string dataType)
    {
        var permissionCode = $"{dataType}.manage";
        return await HasPermissionAsync(userId, permissionCode);
    }
}
